import SwiftUI
import UIKit
import ColorThiefSwift
import Kingfisher




// 缓存图片的管理类
class ImageCacheDominantColor {
    static let shared = ImageCacheDominantColor()
    
    private let cacheDirectoryURL: URL
    
    init() {
        let fileManager = FileManager.default
        let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
        cacheDirectoryURL = cachesDirectory.appendingPathComponent("ImageCacheDominantColor")
        
        // 如果缓存目录不存在，创建它
        if !fileManager.fileExists(atPath: cacheDirectoryURL.path) {
            try? fileManager.createDirectory(at: cacheDirectoryURL, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    // 获取缓存文件路径
    func cachedURL(for url: URL) -> URL {
        return cacheDirectoryURL.appendingPathComponent(url.lastPathComponent)
    }
    
    // 检查缓存中是否存在该图片
    func isCached(url: URL) -> Bool {
        let cachedURL = cachedURL(for: url)
        return FileManager.default.fileExists(atPath: cachedURL.path)
    }
    
    // 从网络加载图片并缓存，并提取主色
    func loadImage(from url: URL, completion: @escaping (UIImage?, Color?) -> Void) {
        // 如果缓存中已有图片，直接加载缓存
        if isCached(url: url) {
            let cachedURL = cachedURL(for: url)
            if let image = UIImage(contentsOfFile: cachedURL.path) {
                // 提取主色
                // 提取主色
                DispatchQueue.global(qos: .userInitiated).async {
                    let dominantColor = self.extractDominantColor(from: image)
                    DispatchQueue.main.async {
                        completion(image, dominantColor)
                    }
                }
                //                completion(image, dominantColor)
                return
            }
        }
        
        // 否则从网络加载图片并缓存
        URLSession.shared.dataTask(with: url) { data, _, error in
            guard let data = data, error == nil, let image = UIImage(data: data) else {
                completion(nil, nil)
                return
            }
            
            // 缓存图片到本地
            let cachedURL = self.cachedURL(for: url)
            try? data.write(to: cachedURL)
            
            // 提取主色
            DispatchQueue.global(qos: .userInitiated).async {
                let dominantColor = self.extractDominantColor(from: image)
                DispatchQueue.main.async {
                    completion(image, dominantColor)
                }
            }
        }.resume()
    }
    
    // 提取主色的方法
    private func extractDominantColor(from image: UIImage) -> Color? {
        // 使用 ColorThief 或其他库提取主色
        if let dominantColor = ColorThief.getColor(from: image)?.makeUIColor() {
            return Color(dominantColor)
        }
        return nil
    }
    
}

struct CachedImageView2: View {
    let imageURL: String
    @State private var loadedImage: UIImage? = nil
    @State private var isLoading: Bool = true
    @State private var error: Bool = false
    @State private var hasAppeared: Bool = false  // 控制是否开始加载
    @State private var imageOpacity: Double = 0.0  //
    @Binding var dominantColor:Color
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                Group {
                    if let loadedImage = loadedImage {
                        // 图片加载完成，显示图片
                        Image(uiImage: loadedImage)
                            .resizable()
                            .scaledToFill()
                            .frame(width: geometry.size.width, height: geometry.size.height)
                            .clipped()
                            .opacity(self.imageOpacity)  //
                            .onAppear {
                                // 每次视图进入屏幕时，重置透明度并触发动画
                                withAnimation(.easeInOut(duration: 0.5)) {
                                    self.imageOpacity = 1.0
                                }
                            }
                            .onDisappear {
                                // 每次离开屏幕时，将透明度重置为0
                                self.imageOpacity = 0.0
                            }
                    } else if isLoading {
                        // 显示加载指示器
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            .frame(width: geometry.size.width, height: geometry.size.height)
                    } else {
                        // 显示错误提示或占位符图片
                        
                        Image("DfImg")
                            .resizable()
                            .scaledToFill()
                            .frame(width: geometry.size.width, height: geometry.size.height)
                            .clipped()
                    }
                }
            }
            .onAppear {
                // 只有在视图出现在屏幕上时才开始加载图片
                if !hasAppeared {
                    hasAppeared = true
                    loadImage()
                }
            }
        }
    }
    
    // 图片加载方法
    private func loadImage() {
        if let url = URL(string: imageURL) {
            ImageCacheDominantColor.shared.loadImage(from: url) { image,dominantColor in
                if let image = image {
                    self.loadedImage = image
                    self.dominantColor = dominantColor ?? Color("BgColor1")
                    // 添加延迟显示加载的图片（0秒延迟，马上显示）
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0) {
                        self.isLoading = false
                    }
                } else {
                    self.error = true
                    self.isLoading = false
                }
                // 初始时显示 loading
                self.isLoading = true
            }
        } else {
            self.error = true
            self.isLoading = false
        }
    }
    
}

struct CachedImageView: View {
    let imageURL: String
    @State private var isLoading: Bool = true
    @State private var error: Bool = false
    @State private var imageOpacity: Double = 0.0  // 控制图片透明度，添加过渡动画
    
    // 一次性设置缓存策略，避免每次渲染时都进行设置
    static let cache = ImageCache.default
    
    static func configureCache() {
        let cache = ImageCache.default
        // 设置内存缓存和磁盘缓存的最大大小
        cache.memoryStorage.config.totalCostLimit = 100 * 1024 * 1024  // 内存缓存最大 50MB
        cache.diskStorage.config.sizeLimit = 1000 * 1024 * 1024  // 磁盘缓存最大 100MB
        
        // 清理已过期的磁盘缓存
        cache.cleanExpiredDiskCache()
    }
    
    // 在视图生命周期中只配置一次缓存
    init(imageURL: String) {
        self.imageURL = imageURL
        CachedImageView.configureCache()
    }
    
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                KFImage(URL(string: imageURL))
                    .resizable()
                    .scaledToFill()
                    .aspectRatio(contentMode: .fill)  // 填充容器并裁剪
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .clipped()
                    .opacity(self.imageOpacity)  // 使用过渡动画控制透明度
                    .onAppear {
                        withAnimation(.easeInOut(duration: 0.5)) {
                            self.imageOpacity = 1.0
                        }
                    }
                    .onDisappear {
                        // 每次离开屏幕时，将透明度重置为0
                        self.imageOpacity = 0.0
                    }
            }
            .onAppear {
                // 只有在视图出现在屏幕上时才开始加载图片
                loadImage()
            }
        }
    }
    
    // 使用 Kingfisher 加载图片
    private func loadImage() {
        // KFImage 自动处理缓存和加载，加载完成后会触发 UI 更新
        self.isLoading = true
    }
}

struct CachedImageViewHeight: View {
    let imageURL: String
    @State private var isLoading: Bool = true
    @State private var error: Bool = false
    @State private var imageOpacity: Double = 0.0  // 控制图片透明度，添加过渡动画
    
    var body: some View {
        ZStack {
            KFImage(URL(string: imageURL))
                .resizable()
                .scaledToFill()
                .aspectRatio(contentMode: .fit)
                .clipped()
                .opacity(self.imageOpacity)  // 使用过渡动画控制透明度
                .onAppear {
                    withAnimation(.easeInOut(duration: 0.5)) {
                        self.imageOpacity = 1.0
                    }
                }
                .onDisappear {
                    // 每次离开屏幕时，将透明度重置为0
                    self.imageOpacity = 0.0
                }
        }
        .onAppear {
            // 只有在视图出现在屏幕上时才开始加载图片
            loadImage()
        }
    }
    
    // 使用 Kingfisher 加载图片
    private func loadImage() {
        // KFImage 自动处理缓存和加载，加载完成后会触发 UI 更新
        self.isLoading = true
    }
}


#Preview {
    CachedImageViewHeight(imageURL: "http://www.cosck.com:444/usb/comic/cover/23/659fcc50d65b2261e79c723c.jpg")
}
